<template>
  <div class="dashboard-container">
    <el-row :gutter="20">
      <!-- 统计卡片 -->
      <el-col :span="6" v-for="(item, index) in statisticsData" :key="index">
        <el-card class="statistics-card" shadow="hover">
          <div class="card-content">
            <div class="card-icon" :style="{ backgroundColor: item.color }">
              <el-icon>
                <component :is="getIconComponent(item.icon)" />
              </el-icon>
            </div>
            <div class="card-info">
              <div class="card-value" :class="{ 'profit': item.change > 0, 'loss': item.change < 0 }">
                {{ item.value }}
                <span v-if="item.change !== undefined" class="change-indicator">
                  {{ item.change > 0 ? '+' : '' }}{{ item.change }}%
                </span>
              </div>
              <div class="card-title">{{ item.title }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="chart-row">
      <!-- 实时价格走势 -->
      <el-col :span="12">
        <el-card class="chart-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span>BTC 价格走势</span>
              <el-button type="primary" size="small" @click="refreshPrices" :loading="isLoading">
                刷新
              </el-button>
            </div>
          </template>
          <div ref="priceChart" style="height: 280px;"></div>
        </el-card>
      </el-col>
      
      <!-- 交易量统计 -->
      <el-col :span="12">
        <el-card class="chart-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span>交易量分布</span>
            </div>
          </template>
          <div ref="volumeChart" style="height: 280px;"></div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="table-row">
      <!-- 最近交易 -->
      <el-col :span="24">
        <el-card class="table-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span>最近交易记录</span>
              <el-button class="header-button" type="text" @click="viewAllTrades">查看全部</el-button>
            </div>
          </template>
          <el-table :data="recentTrades" style="width: 100%">
            <el-table-column prop="time" label="时间" width="150" />
            <el-table-column prop="symbol" label="交易对" width="120" />
            <el-table-column prop="type" label="类型" width="80">
              <template #default="scope">
                <el-tag :type="scope.row.type === '买入' ? 'success' : 'danger'" size="small">
                  {{ scope.row.type }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="price" label="价格" width="120" />
            <el-table-column prop="amount" label="数量" width="120" />
            <el-table-column prop="total" label="总额" width="120" />
            <el-table-column prop="profit" label="盈亏">
              <template #default="scope">
                <span :class="{ 'profit': scope.row.profit > 0, 'loss': scope.row.profit < 0 }">
                  {{ scope.row.profit > 0 ? '+' : '' }}{{ scope.row.profit.toFixed(2) }}%
                </span>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>

    <!-- 策略性能概览 -->
    <el-row :gutter="20">
      <el-col :span="12">
        <el-card class="performance-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span>策略性能</span>
              <el-tag type="success" size="small">在线</el-tag>
            </div>
          </template>
          <div class="performance-stats">
            <div class="stat-item">
              <div class="stat-label">总收益率</div>
              <div class="stat-value profit">+12.35%</div>
            </div>
            <div class="stat-item">
              <div class="stat-label">胜率</div>
              <div class="stat-value">68.4%</div>
            </div>
            <div class="stat-item">
              <div class="stat-label">最大回撤</div>
              <div class="stat-value loss">-5.2%</div>
            </div>
            <div class="stat-item">
              <div class="stat-label">夏普比率</div>
              <div class="stat-value">1.45</div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="12">
        <el-card class="alert-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span>系统警告</span>
              <el-badge :value="alerts.length" type="warning" />
            </div>
          </template>
          <div class="alert-list">
            <div v-for="(alert, index) in alerts" :key="index" class="alert-item">
              <el-icon class="alert-icon" :class="alert.type">
                <component :is="getAlertIcon(alert.type)" />
              </el-icon>
              <div class="alert-content">
                <div class="alert-title">{{ alert.title }}</div>
                <div class="alert-time">{{ alert.time }}</div>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { ref, reactive, onMounted, onUnmounted } from 'vue'
import * as echarts from 'echarts'
import { ElMessage } from 'element-plus'

export default {
  name: 'Dashboard',
  setup() {
    const isLoading = ref(false)
    const priceChart = ref(null)
    const volumeChart = ref(null)
    let priceChartInstance = null
    let volumeChartInstance = null

    // 统计数据
    const statisticsData = ref([
      {
        title: '当前总资产',
        value: '$25,468.32',
        change: 2.34,
        icon: 'el-icon-wallet',
        color: '#409EFF'
      },
      {
        title: '今日盈亏',
        value: '$+342.67',
        change: 1.28,
        icon: 'el-icon-trend-charts',
        color: '#67C23A'
      },
      {
        title: '交易次数',
        value: '156',
        change: -0.45,
        icon: 'el-icon-data-line',
        color: '#E6A23C'
      },
      {
        title: '活跃策略',
        value: '3',
        change: 0,
        icon: 'el-icon-cpu',
        color: '#F56C6C'
      }
    ])

    // 最近交易
    const recentTrades = ref([
      {
        time: '10:23:45',
        symbol: 'BTC/USDT',
        type: '买入',
        price: '$45,234.56',
        amount: '0.025',
        total: '$1,130.86',
        profit: 2.34
      },
      {
        time: '10:18:30',
        symbol: 'ETH/USDT',
        type: '卖出',
        price: '$3,245.78',
        amount: '0.5',
        total: '$1,622.89',
        profit: -1.25
      },
      {
        time: '10:15:22',
        symbol: 'BTC/USDT',
        type: '买入',
        price: '$45,120.34',
        amount: '0.01',
        total: '$451.20',
        profit: 0.89
      },
      {
        time: '10:12:10',
        symbol: 'SOL/USDT',
        type: '卖出',
        price: '$156.78',
        amount: '2.5',
        total: '$391.95',
        profit: 3.45
      }
    ])

    // 系统警告
    const alerts = ref([
      {
        type: 'warning',
        title: 'BTC价格大幅波动',
        time: '2分钟前'
      },
      {
        type: 'info',
        title: '策略回测完成',
        time: '5分钟前'
      },
      {
        type: 'success',
        title: '交易执行成功',
        time: '8分钟前'
      }
    ])

    // 获取图标组件名称
    const getIconComponent = (iconName) => {
      const iconMap = {
        'el-icon-wallet': 'Wallet',
        'el-icon-trend-charts': 'TrendCharts',
        'el-icon-data-line': 'DataLine',
        'el-icon-cpu': 'Cpu'
      }
      return iconMap[iconName] || 'More'
    }

    // 获取警告图标
    const getAlertIcon = (type) => {
      const iconMap = {
        'warning': 'Warning',
        'info': 'InfoFilled',
        'success': 'SuccessFilled',
        'error': 'CircleCloseFilled'
      }
      return iconMap[type] || 'InfoFilled'
    }

    // 刷新价格数据
    const refreshPrices = async () => {
      isLoading.value = true
      try {
        // 模拟获取数据
        await new Promise(resolve => setTimeout(resolve, 1000))
        updatePriceChart()
        ElMessage({
          message: '价格数据已更新',
          type: 'success'
        })
      } catch (error) {
        ElMessage({
          message: '获取数据失败',
          type: 'error'
        })
      } finally {
        isLoading.value = false
      }
    }

    // 查看所有交易
    const viewAllTrades = () => {
      ElMessage({
        message: '跳转到交易页面',
        type: 'info'
      })
    }

    // 初始化价格图表
    const initPriceChart = () => {
      if (!priceChart.value) return
      
      priceChartInstance = echarts.init(priceChart.value)
      updatePriceChart()
    }

    // 更新价格图表
    const updatePriceChart = () => {
      if (!priceChartInstance) return
      
      // 生成模拟数据
      const hours = []
      const prices = []
      const basePrice = 45000
      
      for (let i = 0; i < 24; i++) {
        const hour = (new Date().getHours() - 23 + i + 24) % 24
        hours.push(hour + ':00')
        prices.push(basePrice + (Math.random() - 0.5) * 2000)
      }
      
      const option = {
        tooltip: {
          trigger: 'axis',
          formatter: '时间: {b}<br/>价格: ${c}'
        },
        xAxis: {
          type: 'category',
          data: hours,
          boundaryGap: false
        },
        yAxis: {
          type: 'value',
          scale: true,
          axisLabel: {
            formatter: '${value}'
          }
        },
        series: [{
          data: prices,
          type: 'line',
          smooth: true,
          lineStyle: {
            color: '#409EFF',
            width: 2
          },
          areaStyle: {
            color: {
              type: 'linear',
              x: 0, y: 0, x2: 0, y2: 1,
              colorStops: [
                { offset: 0, color: 'rgba(64, 158, 255, 0.3)' },
                { offset: 1, color: 'rgba(64, 158, 255, 0.1)' }
              ]
            }
          }
        }]
      }
      
      priceChartInstance.setOption(option)
    }

    // 初始化交易量图表
    const initVolumeChart = () => {
      if (!volumeChart.value) return
      
      volumeChartInstance = echarts.init(volumeChart.value)
      
      const option = {
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        series: [{
          name: '交易量',
          type: 'pie',
          radius: '60%',
          data: [
            { value: 35, name: 'BTC' },
            { value: 25, name: 'ETH' },
            { value: 20, name: 'BNB' },
            { value: 15, name: 'SOL' },
            { value: 5, name: '其他' }
          ],
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }]
      }
      
      volumeChartInstance.setOption(option)
    }

    // 组件挂载
    onMounted(() => {
      initPriceChart()
      initVolumeChart()
      
      // 自动刷新价格数据
      const interval = setInterval(() => {
        updatePriceChart()
      }, 30000) // 30秒刷新一次
      
      onUnmounted(() => {
        clearInterval(interval)
        if (priceChartInstance) priceChartInstance.dispose()
        if (volumeChartInstance) volumeChartInstance.dispose()
      })
    })
    
    return {
      statisticsData,
      recentTrades,
      alerts,
      isLoading,
      priceChart,
      volumeChart,
      getIconComponent,
      getAlertIcon,
      refreshPrices,
      viewAllTrades
    }
  }
}
</script>

<style scoped>
.dashboard-container {
  padding: 20px;
}

.statistics-card {
  margin-bottom: 20px;
}

.card-content {
  display: flex;
  align-items: center;
}

.card-icon {
  width: 60px;
  height: 60px;
  border-radius: 8px;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-right: 15px;
}

.card-icon .el-icon {
  font-size: 30px;
  color: #fff;
}

.card-info {
  flex: 1;
}

.card-value {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 5px;
  display: flex;
  align-items: center;
  gap: 10px;
}

.change-indicator {
  font-size: 14px;
  font-weight: normal;
}

.card-title {
  font-size: 14px;
  color: #909399;
}

.profit {
  color: #67C23A;
}

.loss {
  color: #F56C6C;
}

.chart-row {
  margin-bottom: 20px;
}

.chart-card {
  height: 350px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-button {
  padding: 0;
  font-size: 14px;
}

.table-row {
  margin-bottom: 20px;
}

.table-card {
  margin-bottom: 20px;
}

.performance-card,
.alert-card {
  margin-bottom: 20px;
}

.performance-stats {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
}

.stat-item {
  text-align: center;
  padding: 15px;
  background-color: #f8f9fa;
  border-radius: 8px;
}

.stat-label {
  font-size: 14px;
  color: #909399;
  margin-bottom: 8px;
}

.stat-value {
  font-size: 20px;
  font-weight: bold;
  color: #303133;
}

.alert-list {
  max-height: 280px;
  overflow-y: auto;
}

.alert-item {
  display: flex;
  align-items: center;
  padding: 12px 0;
  border-bottom: 1px solid #f0f0f0;
}

.alert-item:last-child {
  border-bottom: none;
}

.alert-icon {
  font-size: 20px;
  margin-right: 12px;
}

.alert-icon.warning {
  color: #E6A23C;
}

.alert-icon.info {
  color: #409EFF;
}

.alert-icon.success {
  color: #67C23A;
}

.alert-icon.error {
  color: #F56C6C;
}

.alert-content {
  flex: 1;
}

.alert-title {
  font-size: 14px;
  color: #303133;
  margin-bottom: 4px;
}

.alert-time {
  font-size: 12px;
  color: #909399;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .dashboard-container {
    padding: 10px;
  }
  
  .performance-stats {
    grid-template-columns: 1fr;
  }
  
  .card-value {
    font-size: 18px;
  }
  
  .chart-card {
    height: 250px;
  }
}
</style>